Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
將陣列中為0的元素,移至陣列最後方。
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
可用splice
方法將0取出,再用push
方法添加至陣列的後方。
var moveZeroes = function (nums) {
let x = 0;
for (let i = 0; i < nums.length - x; i++) {
if (nums[i] === 0) {
nums.push(parseInt(nums.splice(i, 1).join('')));
i--;
x++;
}
}
return nums;
};